<!--单据明细 和 统计-->
<template>
    <div>
        <a-row :gutter="[16,8]">
            <a-col :span="24">
                <div class="search-btn-box">
                    <!-- <div class="item-big" @click="searchDynamic">
                        <span>
                            <a-icon class="icon-searh" type="file-search" />
                        </span><br>
                        <span>查询</span>
                    </div> -->
                    <div class="item-small">
                        <ul>
                            <li class="item-plan" :class="planActive == 0?'active':''" @click="getSystemplan()">所有</li>
                            <li class="item-plan" :title="item.programmeName" :class="item.id == planActive?'active':''" v-for="(item,index) in myPlanList" :key="index" @click="changePlane(item)">
                                {{item.programmeName}}</li>
                            <li class="item-plan" @click="searchDynamic">
                                <!-- <a-icon class="icon-searh-btn" type="file-search" /> 查询 -->
                                自定查询
                                <a-icon class="icon-searh-btn" type="search" />
                            </li>
                        </ul>
                        <!-- <a-tag class="item-plan" :color="planActive == 0?'#108ee9':'#2db7f5'" @click="getSystemplan()">
                            默认方案
                        </a-tag>
                        <a-tag class="item-plan" v-for="(item,index) in myPlanList" :key="index" :color="item.id == planActive?'#108ee9':'#2db7f5'" @click="changePlane(item)">
                            {{item.programmeName}}
                        </a-tag> -->
                    </div>
                </div>
            </a-col>
            <a-col :span="24" class="details-table-wrapper">
                <!-- :row-selection="rowSelection" -->
                <a-table @change="handleTableChange" :row-selection="routeDDDD?rowSelection:''" style="min-height:250px;" :id="'details_list_tb' + componentType" :columns="datailColumns" :data-source="datailsDataSource" :pagination="detailPagination" :scroll="{ x: 1000, y: 500 }" bordered>
                    <template v-for="col in slotArray" :slot="col" slot-scope="text">
                        <!-- <div data-key="" v-if="text"> -->
                        <div data-key="">
                            {{text | NumFormat}}
                        </div>
                    </template>
                    <template slot="baseUnit" slot-scope="text">
                        {{text | unitFormart}}
                    </template>
                    <template slot="subUnit" slot-scope="text">
                        {{text | unitFormart}}
                    </template>
                    <template slot="sourceVoucherType" slot-scope="text">
                        {{conversionOrderName(text)}}
                    </template>
                    <template slot="voucherState" slot-scope="text,record,index">
                        <!-- -1:待提交 0：待审核 1：已审核 2：已确认 10：关闭 -->
                        <div v-if='text != 2'>
                            {{text==-1?'待提交':text==0?'待审核':text==1?'已审核':text==10?'关闭':''}}
                        </div>
                        <div v-else>
                            {{text==2 && record.iom_receiveDeliverType == '1' ?'已入库':text==2 && record.iom_receiveDeliverType == '2' ?'已出库':''}}
                        </div>
                    </template>
                </a-table>
            </a-col>
        </a-row>

        <!--查询弹窗-->
        <search-wrapper ref="searchWrapperRef" :componentType="componentType" @newPlan="getMyselfPlan" @changePlane="changePlane" :reportCode="reportCode" :businessType="businessType" :excludeHeadOrFoodColumn="excludeHeadOrFoodColumn"></search-wrapper>
    </div>
</template>
<script>
import searchWrapper from '@/components/OrderDynamicForm/searchWrapper'
import { myplan, systemplan, detailsList, exportTable } from '@/api/erp/reportProgramme';

import { IdFieldToNameField } from "@/utils/customize"
import { getAction, postAction } from "@/api/manage";
import { conversionOrderName } from "@/utils/tool/parametric-switch"
import { Controlwidth } from "@/utils/antTableComponents";

let units = [];//计量单位所有数据

export default {
    components: {
        searchWrapper
    },
    props: {
        reportCode: {
            type: String
        },
        componentType: {
            type: Number
        },
        businessType: { //生产领退补的类型区分
            type: Number
        },
        createdShow: {
            type: Boolean,
            default: false
        },
        getListType: {
            type: Boolean,//是否从新拉取数据
            default: false
        },
        checkedBox: { //是否需要复选框功能
            type: Boolean,
            default: false
        },
        dataSourceCode: {
            type: String
        },
        basePostData: {
            type: Object,
            default: {
                someBusinessType: null   //指定业务类型
            }
        },
        excludeHeadOrFoodColumn: {
            type: Array,
            default: null
        },
    },

    updated () {
        Controlwidth("details_list_tb1", 100)
        Controlwidth("details_list_tb2", 100)
    },

    watch: {
        getListType () {
            if (this.getListType == true) {
                this.getSystemplan();
                this.getMyselfPlan();
                this.$emit('update:getListType', false)
            }
        }
    },
    data () {
        return {
            routeDDDD: this.$route.path == '/production/productionProcessReport' ? true : false,//处理工序汇报要显示复选框
            datailColumns: [],//明细列表columns
            systemPlan: [],//系统方案
            myPlanList: [],//自定义方案列表
            planActive: 0,
            shoTotal: 0,
            isSum: false,
            detailPagination: {
                size: "small",
                current: 1,
                pageSize: 10,
                total: 0,
                showTotal: total => {
                    return (
                        <div>
                            共 {this.isSum ? total - Math.ceil(this.detailPagination.total / this.detailPagination.pageSize) : total} 条数据，每页
                            <a-input style="height:22px !important;width:3.2rem;"
                                value={this.detailPagination.pageSize}
                                min={5}
                                max={500}
                                size="small"
                                step={1}
                                onPressEnter={e => this.changePageSize(e)}
                            />
                            条
                        </div>
                    );
                },
                onChange: (page, pageSize) => {
                    this.detailPagination.current = page;
                    this.detailPagination.pageSize = pageSize;
                    this.handleTableChange({
                        current: page,
                        pageSize: pageSize
                    })
                },
                showQuickJumper: false,
                showLessItems: false,
            },
            slotArray: [],          //小数或者整数字段集合
            isTemporary: false,     //是否是临时搜索
            TemporaryData: [],      //临时搜索数据
            newMyClickPlan: [],
            requestData: [],
            exportRequestData: {},   //导出请求参数
        }
    },
    computed: {
        rowSelection () {
            if (this.checkedBox) {
                return {
                    onChange: (e, s) => {
                        this.$emit('checkChange', s);
                    },
                    getCheckboxProps: record => ({
                        props: {
                            disabled: record.wpcd_status >= 2
                        },
                    }),
                    columnWidth: 40

                }
            } else {
                return {}
            }
        }
    },
    mounted () {
        //工序汇报默认展示showModel为detail所以开始就要请求
        if (this.createdShow) {
            this.getSystemplan();
        }
    },
    created () {
        // this.getSystemplan();
        // this.getMyselfPlan();
        // this.getUnit();
    },
    methods: {
        conversionOrderName,
        //改变分页大小
        changePageSize (e) {
            const value = e.target.value;
            if (value <= 1) {
                this.$message.warning('每页必须大于2条数据');
                return;
            }
            let size = Number.parseInt(value);
            if (!size) {
                size = 20;
            }
            if (size > 500) {
                size = 500;
            }
            this.detailPagination.current = 1;
            this.detailPagination.pageSize = size;
            this.handleTableChange({
                current: 1,
                pageSize: size
            })
        },
        //动态查询搜索条件
        searchDynamic () {
            this.$refs.searchWrapperRef.showModel();
        },
        //获取系统方案
        getSystemplan () {
            let { excludeHeadOrFoodColumn } = this;
            this.planActive = 0;
            this.isTemporary = false;
            systemplan({ reportCode: this.reportCode }).then((res) => {
                console.log("获取系统方案");
                if (res.code == 200) {
                    let systemData = res.data
                    if (excludeHeadOrFoodColumn) {
                        systemData = res.data.filter(item => !((item.fieldSource == '表头' || item.fieldSource == '表尾') && excludeHeadOrFoodColumn.indexOf(item.code) > -1));
                    }
                    this.systemPlan = systemData;

                    this.handleJoinCloumns(systemData);
                    this.handlerSearch('clickSlef');
                }
            }).catch((e) => {
                // this.$message.error('请求出错', 1)
            })
        },
        //获取个人方案列表
        getMyselfPlan () {
            myplan({ reportCode: this.reportCode, businessType: this.businessType ? this.businessType : null }).then((res) => {
                if (res.code == 200) {
                    this.myPlanList = res.data;
                }
            }).catch((e) => {
                this.$message.error('获取个人方案列表_请求出错', 1)
            })
            console.log("获取个人方案列表：", this.myPlanList)
        },
        //点击自定方案事件
        changePlane (data) {

            console.log('点击自定义方案', data)

            let d = { ...data };
            let list = JSON.parse(d.programmeJson);

            //判断是否是弹窗 返回回来的临时搜索
            if (d.isTemporary) {
                this.isTemporary = d.isTemporary;
                this.TemporaryData = JSON.parse(d.programmeJson);
            } else {
                this.isTemporary = false;
            }


            this.handleJoinCloumns(list);
            this.planActive = d.id;

            this.newMyClickPlan = d.programmeJson;//最新数据

            this.handlerSearch('clickSlef');


            console.log('当前搜索的数据', this.datailColumns)
        },
        //获取明细列表数据
        handlerSearch (t) {

            let { requestData, basePostData } = this;

            if (t == 'clickSlef') {
                this.detailPagination.current = 1;
            }
            let baseRequestData = {
                erpReportDesignList: {},
                page: {
                    'current': this.detailPagination.current,
                    'size': this.detailPagination.pageSize,
                },
            }


            Object.assign(baseRequestData, basePostData);
            Object.assign(baseRequestData, requestData);

            if (this.planActive == 0) {
                //点击系统方案后
                if (this.isTemporary) {
                    baseRequestData.erpReportDesignList = this.TemporaryData;//系统方案临时搜索
                } else {
                    baseRequestData.erpReportDesignList = this.systemPlan;//系统方案默认搜索
                }
            } else {
                // this.myPlanList.forEach(plan => {
                //     if (plan.id == this.planActive) {
                //         requestData.erpReportDesignList = JSON.parse(plan.programmeJson);
                //     }
                // });

                //点击自定义方案后
                baseRequestData.erpReportDesignList = JSON.parse(this.newMyClickPlan);
            }
            // baseRequestData.dataSource = this.dataSourceCode ? this.dataSourceCode : null;


            if (baseRequestData.erpReportDesignList.some(res => res.onSummary)) {
                this.isSum = true;
                baseRequestData.page.size = this.detailPagination.pageSize - 1;
            } else {
                this.isSum = false;
            }

            //复制请求参数，用于导出请求
            this.exportRequestData = _.cloneDeep(baseRequestData);

            detailsList(baseRequestData).then((res) => {
                if (res.code == 200) {

                    this.datailsDataSource = res.data.records.map(v => {
                        return { ...v, key: v.id }
                    });
                    console.log('明细列表返回的列表参数：', res.data, " this.datailsDataSource:", this.datailsDataSource);
                    this.detailPagination.total = res.data.total;
                    if (res.data.records.length > 1) {
                        let endData = res.data.records[res.data.records.length - 1];
                        // if (endData.isSum) {
                        //     this.detailPagination.pageSize = res.data.size - 1;
                        // this.detailPagination.total = this.detailPagination.total + parseInt(this.detailPagination.total / res.data.size);
                        // this.shoTotal = res.data.total;
                        // } else {
                        this.shoTotal = res.data.total;
                        // }
                    }
                    this.$forceUpdate();//强制更新
                }
            }).catch((e) => {
                // this.$message.error('请求出错', 1)
            })
        },
        //组装cloumns
        handleJoinCloumns (data) {

            let list = data;
            this.datailColumns = [];
            list.forEach(detail => {
                // let code = detail.tableName.split(" ")[1] + '_' + detail.code;
                // if (detail.columnType == '搜索选择') {
                //     code = IdFieldToNameField(code)
                // }

                let codeA = detail.code;
                if (detail.columnType == '搜索选择' || detail.columnType == '模糊搜索') {
                    codeA = IdFieldToNameField(codeA)
                }
                let s = detail.tableName.trim();
                let code = s.substring(s.lastIndexOf(" ") + 1) + '_' + codeA;
                // console.log("列", code)
                // let code = detail.tableName.split(" ")[1] + '_' + codeA;

                let textAlign = 'left';
                if (detail.columnType == '小数' || detail.columnType == '整数') {
                    textAlign = 'right';
                }

                let cloumns = {
                    title: detail.name,
                    dataIndex: code,
                    key: code,
                    width: detail.columnWidth,
                    ellipsis: true,
                    align: textAlign,
                    sorter: true,
                    customCell: (record, rowIndex) => {		//在此处定义
                        if (record.isSum == true) {
                            return { style: { 'color': '#222', 'font-size': '12px', 'font-weight': 'bold' } }    //return 想要设置的样式
                        }
                    }
                }

                //业务类型 1.普通采购 2.固定资产 3.普通销售 96:销售退货(冲抵) 97: 采购退货(冲抵) 98.销售退货 99.采购退货
                // if (detail.code == 'businessType') {
                //     cloumns.scopedSlots = { customRender: 'businessType' }
                // }

                if (detail.columnType == '下拉选择' && detail.val && detail.code != 'voucherState') {
                    let valList = [];
                    try {
                        valList = JSON.parse(detail.val);
                    } catch (error) {
                        return "";
                    }
                    cloumns.customRender = (text, row, index) => {
                        let findOne = valList.find(f => f.key == text);
                        return findOne ? findOne.label : "";
                    }
                }

                if (detail.columnType == '小数' || detail.columnType == '整数') {
                    this.slotArray.push(detail.code);
                    cloumns.scopedSlots = { customRender: detail.code }
                }

                if (detail.code == 'baseUnit') {//主计量
                    cloumns.scopedSlots = { customRender: 'baseUnit' }
                }
                if (detail.code == 'subUnit') {//辅助计量
                    cloumns.scopedSlots = { customRender: 'subUnit' }
                }

                if (detail.code == 'sourceVoucherType') {//来源单据
                    cloumns.scopedSlots = { customRender: 'sourceVoucherType' }
                }

                if (detail.code == 'voucherState') {//单据状态
                    cloumns.scopedSlots = { customRender: 'voucherState' }
                }
                if (detail.onShow && this.componentType == 1) {
                    //明细
                    this.datailColumns.push(cloumns);
                } else if ((detail.onGroup || detail.onSummary) && this.componentType == 2) {
                    this.datailColumns.push(cloumns);
                }
            });
            this.datailColumns.unshift({
                title: '序号',
                dataIndex: 'number',
                width: 40,
                align: 'center',
                customRender: (text, record, index) => {
                    return index + 1;
                }
            })
            console.log('columns:', this.datailColumns)
            this.$forceUpdate();
        },
        //获取计量单位
        getUnit () {
            let postData = {
                current: 1,
                size: 500,
                unitGroupId: '',
            }
            getAction('/in/unit/pageList', postData).then(response => {
                if (response.code === 200) {
                    console.log(response);
                    units = response.data.records;
                }
            }).catch(error => { });
        },
        //排序
        handleTableChange (pagination, filters, sorter) {
            console.log(pagination, filters, sorter)
            Object.assign(this.detailPagination, {
                current: pagination.current,
                pageSize: pagination.pageSize
            });
            Object.assign(this.requestData, {
                sortField: sorter ? sorter.columnKey : null,
                sortOrder: sorter ? sorter.order : null
            });
            this.handlerSearch();
        },
        //导出
        export (title) {
            this.exportRequestData.filedList = this.datailColumns;
            exportTable(this.exportRequestData).then(res => {
                let url = window.URL.createObjectURL(
                    new Blob([res], { type: "application/vnd.ms-excel" })
                );
                let link = document.createElement("a");
                link.style.display = "none";
                link.href = url;
                link.setAttribute("download", title + ".xls");
                document.body.appendChild(link);
                console.log(link);
                link.click();
            }).catch(error => { });
        }
    },
    filters: {
        unitFormart (id) {
            let act = '';
            if (units.length > 0) {
                for (let i = 0; i < units.length; i++) {
                    if (units[i].id == id) {
                        act = units[i].name;
                    }
                }
            }
            return act;
        }
    }
}
</script>
<style lang="less">
    .search-btn-box {
        display: flex;
        border-bottom: 2px solid #1e9fff;
        margin-top: 4px;
        .item-big {
            flex: 0 0 60px;
            font-size: 14px;
            text-align: center;
            color: #000;
            // font-weight: bold;
            line-height: 20px;
            cursor: pointer;
            .icon-searh {
                font-size: 19px;
                color: rgb(45, 144, 236);
            }
        }
        .item-small {
            ul {
                width: 100%;
                list-style: none;
                padding: 0;
                margin: 0;
                clear: both;
            }
            ul > li {
                float: left;
                // border: 1px solid rgb(162, 187, 203);
                color: #333;
                height: 32px;
                line-height: 32px;
                padding: 0px 10px;
                font-size: 14px;
                margin-right: 5px;
                max-width: 120px;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
            }
            ul > li.active {
                // border: 1px solid rgb(56, 99, 255);
                background: #1e9fff;
                color: #ffffff;
            }
            .icon-searh-btn {
                color: #1e9fff;
            }

            ul > li:hover {
                // border: 1px solid rgb(56, 99, 255);
                background: #1e9fff;
                color: #ffffff;
                .icon-searh-btn {
                    color: #ffffff;
                }
            }
            .item-plan {
                cursor: pointer;
            }
        }
    }
    .details-table-wrapper {
        .ant-table-thead
            > tr
            > th
            .ant-table-header-column
            .ant-table-column-sorters:before {
            left: 5px;
            right: 5px;
        }
    }
</style>